<template>
  <div class="box">
    <div class="head-fixed">
      <div class="head">
        <div class="head-div">
          <img
            src="../../assets/zjt2.png"
            alt=""
            class="back"
            @click="back()"
          />
        </div>
        <div class="head-search">创建简历</div>
        <div @click="save">保存</div>
      </div>
    </div>
    <div class="content">
      <div class="inpBox">
        <span>头像</span>
        <input
          v-show="false"
          type="file"
          accept="image/*"
          @change="triggerFile($event)"
          ref="input"
        />
        <div>
          <img
            src="../../assets/avatar.png"
            v-if="imgUrl === ''"
            alt=""
            @click="openImg"
          />
          <img :src="imgUrl" alt="" v-if="imgUrl !== ''" @click="openImg"/>
          <!--   通过 v-if 里面表达式的结果, 如果为true , 则显示当前行, 反之不显示. v-model按理说是需要和数据库里的字段对应-->
        </div>
      </div>
      <div class="inpBox">
        <span>姓名</span>
        <div>
          <input type="text" v-model="name" placeholder="请输入姓名"/>
        </div>
      </div>
      <div class="inpBox">
        <span>性别</span>
        <div>
          <input type="radio" name="sex" v-model="check" value="0"/><span
        >男</span
        >
          <input type="radio" name="sex" v-model="check" value="1"/><span
        >女</span
        >
        </div>
      </div>
      <div class="inpBox">
        <span>出生日期</span>
        <div>
          <input type="date" v-model="birthday" placeholder="请输入出生日期"/>
        </div>
      </div>
      <div class="inpBox">
        <span>微信</span>
        <div>
          <input type="text" v-model="wx" placeholder="请输入微信"/>
        </div>
      </div>
      <div class="inpBox">
        <span>邮箱</span>
        <div>
          <input type="text" v-model="email" placeholder="请输入邮箱"/>
        </div>
      </div>
      <div class="inpBox">
        <span>职位种类</span>
        <div @click="prop(0)">
          <input
            type="text"
            v-model="postValue"
            placeholder="请选择职位种类"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>工作城市</span>
        <div @click="prop(1)">
          <input
            type="text"
            v-model="cityValue"
            placeholder="请选择工作城市"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>期望薪资</span>
        <div @click="prop(2)">
          <input
            type="text"
            v-model="payValue"
            placeholder="请选择期望薪资"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>求职状态</span>
        <div @click="prop(3)">
          <input
            type="text"
            v-model="stateValue"
            placeholder="请选择求职状态"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>工作年限</span>
        <div @click="prop(4)">
          <input
            type="text"
            v-model="workYear"
            placeholder="请选择工作年限"
            readonly
          />
        </div>
      </div>
    </div>
    <!-- mt是mint-ui，主要是依靠v-model，如果是true则显示出来。通过position去指的popup从哪里弹出，从下部弹出-->
    <mt-popup v-model="postIf" position="bottom">
      <!--p标签代表了第一行，左侧取消，右侧确定-->
      <p class="mt-p">
        <span @click="off(0)">取消</span>
        请选择职位
        <span @click="on(0)">确定</span>
      </p>
      <!--传入一个slots当被选中时候触发一个@change事件-->、
      <!-- 冒号叫做v-band，强制绑定， slots是对象数组，即下拉里的内容，其中的post是通过asios获取到后端的数据，将其替换成真实表中数据-->
      <mt-picker
        :slots="post"
        @change="postChange"
        value-key="positionTitle"
        class="picker"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="cityIf" position="bottom">
      <p class="mt-p">
        <span @click="off(1)">取消</span>
        请选择城市
        <span @click="on(1)">确定</span>
      </p>
      <mt-picker :slots="city" valueKey="name" @change="cityOn"></mt-picker>
    </mt-popup>
    <mt-popup v-model="payIf" position="bottom">
      <p class="mt-p">
        <span @click="off(2)">取消</span>
        请选择薪资
        <span @click="on(2)">确定</span>
      </p>
      <mt-picker
        :slots="payList"
        @change="payChange"
        value-key="salaryRange"
        class="picker"
      ></mt-picker>
    </mt-popup>

    <mt-popup v-model="stateIf" position="bottom">
      <p class="mt-p">
        <span @click="off(3)">取消</span>
        请选择求职状态
        <span @click="on(3)">确定</span>
      </p>
      <mt-picker
        :slots="stateLimit"
        @change="stateChange"
        value-key="jobStatus"
        class="picker"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="YearIf" position="bottom">
      <p class="mt-p">
        <span @click="off(4)">取消</span>
        请选择工作年限
        <span @click="on(4)">确定</span>
      </p>
      <mt-picker
        :slots="workYearList"
        @change="yearChange"
        value-key="workYear"
        class="picker"
      ></mt-picker>
    </mt-popup>
  </div>
</template>

<script>
import {Popup, Picker, Toast} from 'mint-ui'
import threeLevelAddress from '../../assets/address.json'

var postValue = ''
var cityValue = ''
var cityValue2 = ''
var payValue = ''
var stateValue = ''
var workYear = ''
var stateCode = ''
var workYearCode = ''
var payCode = ''
var cityCode = ''
var postCode = ''
export default {
  inject: ['reload'],
  name: 'found',
  components: {
    Popup,
    Picker
  },
  created () {
    // created 在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图
    this.getData()//创建后要获取到下拉里面的真实数据
  },
  mounted () {
    // mounted在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
  },
  // data() 为变量赋值等
  data () {
    return {
      // status为用户身份，0是求职者，1是招聘者
      status: localStorage.status,
      //个人简历信息
      imgUrl: '',
      check: 0,
      file: '',
      name: '',
      birthday: '',
      phone: '',
      wx: '',
      email: '',
      postValue: '',
      postValueId: '',
      postAct: 0,
      postIf: false,
      // post是个数组，数组里有个对象
      post: [
        {
          flex: 1,
          defaultIndex: 0,
          values: [], //键k，其数组里的名字作为下拉列表的值
          className: 'slot1',
          textAlign: 'center'
        },
        {
          divider: true,
          content: '-',
          className: 'slot2'
        },
        {
          flex: 1,
          values: [],
          className: 'slot3',
          textAlign: 'center'
        },
        {
          divider: true,
          content: '-',
          className: 'slot2'
        },
        {
          flex: 1,
          values: [],
          className: 'slot3',
          textAlign: 'center'
        }
      ],
      cityValue: '',
      cityValueId: '',
      cityAct: 0,
      cityIf: false,
      city: [
        {
          flex: 1,
          defaultIndex: 0,
          values: this.getProvinceArr(),//调用了下面的json里的省
          className: 'slot1',
          textAlign: 'center'
        },
        {
          divider: true,
          content: '-',
          className: 'slot2'
        },
        {
          flex: 1,
          values: this.getCityArr('北京市'),
          className: 'slot3',
          textAlign: 'center'
        },
        {
          divider: true,
          content: '-',
          className: 'slot4'
        },
        {
          flex: 1,
          values: this.getCountyArr('北京市', '北京市'),
          className: 'slot5',
          textAlign: 'center'
        }
      ],
      payValue: '',
      payAct: 0,
      payIf: false,
      payList: [
        {
          values: []
        }
      ],
      workYearList: [
        {
          values: []
        }
      ],
      payValueId: '',
      stateValueId: '',
      workYearId: '',
      stateValue: '',
      stateAct: 0,
      stateIf: false,
      stateLimit: [
        {
          values: []
        }
      ],
      workYear: '',
      yearAct: 0,
      YearIf: false,
      images: ''
    }
  },
  methods: {
    back () {
      this.$router.go(-1) //返回上一层
    },
    triggerFile: function (event) {
      let file = event.target.files[0]
      let url = ''
      var reader = new FileReader()
      reader.readAsDataURL(file)
      let that = this
      reader.onload = function (e) {
        url = this.result.substring(this.result.indexOf(',') + 1)
        that.imgUrl = 'data:image/png;base64,' + url
        that.images = url//获取文件流，获取base64
      }
    },
    openImg () {
      this.$refs.input.click()
    },
    notEmpty (val) {
      const re = new RegExp('^[ ]+$') //正则，去除空字符。匹配是否为空
      return !(val == null || val === '' || typeof (val) === 'undefined' || re.test(val))
    },
    save () {
      if (!this.notEmpty(this.images)) {
        return Toast('请上传头像')
      }
      if (!this.notEmpty(this.name)) {
        return Toast('请输入姓名')
      }
      if (!this.notEmpty(this.birthday)) {
        return Toast('请选择出生日期')
      }
      if (!this.notEmpty(this.wx)) {
        return Toast('请输入微信')
      }
      if (!this.notEmpty(this.email)) {
        return Toast('请输入邮箱')
      }
      if (!this.notEmpty(this.postValueId)) {
        return Toast('请选择职位种类')
      }
      if (!this.notEmpty(this.cityValueId)) {
        return Toast('请选择工作城市')
      }
      if (!this.notEmpty(this.payValueId)) {
        return Toast('请选择期望薪资')
      }
      if (!this.notEmpty(this.stateValueId)) {
        return Toast('请选择求职状态')
      }
      if (!this.notEmpty(this.workYearId)) {
        return Toast('请选择工作年限')
      }
      this.$http({
        url: this.AppURL + '/userResume/save',
        method: 'post',
        data: {
          userName: this.name,
          resumePortrait: this.images,
          userId: localStorage.getItem('userId'),
          age: this.getAge(this.birthday),
          sex: this.check,
          birthdate: this.birthday,
          tel: this.phone,
          wechat: this.wx,
          email: this.email,
          positionType: this.postValueId,
          cityId: this.cityValueId,
          resumeSalary: this.payValueId,
          jobStatus: this.stateValueId,
          workYear: this.workYearId
        }
      }).then(({data}) => {
        // 成功处理
        this.$router.push("/usersResume");
      }).catch(error => {
        // 错误处理
      })
    },
    getAge (strBirthday) {
      var returnAge//返回一个年龄

      var strBirthdayArr = strBirthday.split('-')//中间的-
      var birthYear = strBirthdayArr[0]//定义年的数组
      var birthMonth = strBirthdayArr[1]//定义月的数组
      var birthDay = strBirthdayArr[2]//定义日的数组

      var d = new Date()//new出日期
      var nowYear = d.getFullYear() //这个nowYear是调用了getfullyear的底层方法
      var nowMonth = d.getMonth() + 1
      var nowDay = d.getDate()

      if (nowYear == birthYear) {
        returnAge = 0//同年 则为0岁
      } else {
        var ageDiff = nowYear - birthYear //年之差
        if (ageDiff > 0) { //
          if (nowMonth == birthMonth) {
            var dayDiff = nowDay - birthDay//日之差
            if (dayDiff < 0) {
              returnAge = ageDiff - 1//
            } else {
              returnAge = ageDiff
            }
          } else {
            var monthDiff = nowMonth - birthMonth//月之差
            if (monthDiff < 0) {//小于0说明生日的月份大
              returnAge = ageDiff - 1//相对的额实际年龄要-1
            } else {
              returnAge = ageDiff
            }
          }
        } else {
          returnAge = -1//出生日期不能大于今天
        }
      }
      return returnAge
    },
    getData () {
      this.$http({
        url: this.AppURL + '/userResume/list',
        method: 'post'
      }).then(({data}) => {
        console.log(data)
        let positionTypeList = data.positionTypeList
        let salaryList = data.salaryList
        let jobStatusList = data.jobStatusList
        console.log(positionTypeList[0].list2)
        this.post[0].values = positionTypeList
        this.post[2].values = positionTypeList[0].list2
        this.post[4].values = positionTypeList[0].list2[0].list3
        this.payList[0].values = salaryList
        this.stateLimit[0].values = jobStatusList
        this.workYearList[0].values = data.workYearList
      })
    },
    prop (i) {
      if (i === 0) {
        this.postIf = !this.postIf
      } else if (i === 1) {
        this.cityIf = !this.cityIf
      } else if (i === 2) {
        this.payIf = !this.payIf
      } else if (i === 3) {
        this.stateIf = !this.stateIf
      } else if (i === 4) {
        this.YearIf = !this.YearIf
      }
    },

    postChange (picker, values) { //picker相当于一个选择器组件，下拉会给上方留一段余白，values是选择下拉的内容
      if (values[0]) {
        picker.setSlotValues(1, values[0].list2)
      }
      if (values[1]) {
        picker.setSlotValues(2, values[1].list3)
      }
      if (values[2]) {
        postValue = values[2].positionTitle
        postCode = values[2].id
      }
    },
    cityOn (picker, values) {
      if (this.regionInit) {
        //给市、县赋值， setSlotValues是mint-ui里提供的方法
        picker.setSlotValues(1, this.getCityArr(values[0]['name']))//1代表index是第2个索引(市)。后面的代表value，把第2个索引的内容附上了后面的值，即选中的城市的名字
        picker.setSlotValues(2, this.getCountyArr(values[0]['name'], values[1]['name'])//同上，获得第3个索引(区),把第3个索引的内容附上后面的值，即选中的区的名字
        )
        //取值并赋值
        cityValue = values[2]['name'] //得到第三级的name，付给全局变量cityValue（on下面的）
        cityValue2 = values[2]['code'] //得到第三级的code 付给全局变量cityValue2
        cityCode = values[2]['code'] //得到第三级的code 付给全局变量cityValue2
      } else {
        this.regionInit = true
        cityValue = values[2]['name']
        cityValue2 = values[2]['code']
        cityCode = values[2]['code']
      }
    },
    payChange (picker, values) {
      // 赋予全局变量为选择内容
      if (values[0]) {
        payValue = values[0].salaryRange
        payCode = values[0].id
      }
      // 赋予当前选中的选项的id属性值 用于表单提交
      // this.payValueId = picker.values[0].id;
    },
    stateChange (picker, values) {
      if (values[0]) {
        stateValue = values[0].jobStatus
        stateCode = values[0].id
      }
    },
    yearChange (picker, values) {
      if (values[0]) {
        workYear = values[0].workYear
        workYearCode = values[0].id
      }
    },

    on (i) { //点击确定以后
      // debugger
      if (i === 0) {
        this.postValue = postValue // 并且把全局变量赋予给环境里的postValue，即绑定了input中的v-model
        this.postValueId = postCode
        this.postIf = false //变成了false，即下拉收回，
      } else if (i === 1) {
        this.cityValue = cityValue //付给环境，在环境中显示出来
        this.cityValue2 = cityValue2
        this.cityValueId = cityCode
        this.cityIf = false
      } else if (i === 2) {
        this.payValue = payValue
        this.payValueId = payCode
        this.payIf = false
      } else if (i === 3) {
        this.stateValue = stateValue
        this.stateValueId = stateCode
        this.stateIf = false
      } else if (i === 4) {
        this.workYear = workYear
        this.workYearId = workYearCode
        this.YearIf = false
      }
    },
    off (i) {
      if (i === 0) {
        // this.post = ""; /*自己改过的，以前是post = "" ; */
        this.postIf = false
      } else if (i === 1) {
        cityValue = ''
        this.cityIf = false
      } else if (i === 2) {
        payValue = ''
        this.payIf = false
      } else if (i === 3) {
        stateValue = ''
        this.stateIf = false
      } else if (i === 4) {
        workYear = ''
        this.YearIf = false
      }
    },
    //遍历json，返回省级对象数组
    getProvinceArr () {
      // alert(1111);
      let provinceArr = []
      threeLevelAddress.forEach(function (item) { //threeLevelAddress在最上面已经引入了资源，相当于遍历了这个资源里的address.json
        let obj = {}
        obj.name = item.name
        obj.code = item.code
        provinceArr.push(obj)//只取了address.json里的省
      })
      return provinceArr //遍历以后返回省
    },
    //遍历json，返回市级对象数组
    getCityArr (province) {//如果参数是传递过来的省份
      // console.log("省：" + province);
      let cityArr = []
      threeLevelAddress.forEach(function (item) { //就去循环一个参数
        if (item.name === province) {//让该参数的名字为省级的名字
          item.children.forEach(function (args) {//得到该省下的所以的市
            let obj = {}
            obj.name = args.name
            obj.code = args.code
            cityArr.push(obj)
          })
        }
      })
      return cityArr
    },
    //遍历json，返回县级对象数组
    getCountyArr (province, city) { //把得到的省和市传过来
      // alert(province,city);
      let countyArr = []
      threeLevelAddress.forEach(function (item) {
        if (item.name === province) {//循环得到的省
          item.children.forEach(function (args) {
            if (args.name === city) { //循环得到的市
              args.children.forEach(function (param) {
                let obj = {}
                obj.name = param.name
                obj.code = param.code
                countyArr.push(obj)//取对应的区
              })
            }
          })
        }
      })
      console.log(countyArr)
      return countyArr//返回该区
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
html,
body,
.tac,
.box,
.tab-left,
.tab-left .el-menu {
  height: 100%;
}

.box {
  width: 100%;
  background: #fff;
}

.head-fixed {
  width: 100%;
  height: 43px;
  position: fixed;
  z-index: 999;
}

.head {
  background: #3e63a8;
  color: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.back {
  width: 14px;
  height: 14px;
}

.head div img {
  width: 20px;
  height: 20px;
}

.head-search {
  box-sizing: border-box;
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.content {
  position: relative;
  top: 43px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 20px;
}

.inpBox {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  border-bottom: 1px solid #eee;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
}

.inpBox img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.inpBox input {
  border: 0;
  flex: 1;
  outline: none;
  font-size: 14px;
  height: 30px;
  text-align: right;
}

.inpBox div {
  display: flex;
  align-items: center;
}

.inpBox div input[type="radio"] {
  margin-left: 20px;
  margin-right: 5px;
}

.inpBoxs {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.inpBoxs .inpBox {
  border: 0;
}

.inpBoxs textarea {
  width: 100%;
  height: 150px;
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}
</style>
